package com.lin.java.tool.send.factory;

import cn.hutool.core.collection.CollectionUtil;
import com.lin.java.tool.send.enums.PlatformEnum;
import com.lin.java.tool.send.enums.SendEnum;
import com.lin.java.tool.send.ex.CustomSendException;
import com.lin.java.tool.send.model.Sms;
import com.lin.java.tool.send.sms.SmsStrategy;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;

/**
 * @author linjiang
 * @date 2024/8/19
 * @fn 短信工厂
 */
public class SmsFactory {
    /**
     * 确认使用的平台
     */
    private String platform;

    /**
     * 各种短信配置
     */
    private Map<String, Sms> sms;

    /**
     * 各种短信策略
     */
    private final Map<String, SmsStrategy> strategy = new HashMap<>(16);


    public SmsFactory(String platform, Map<String, Sms> sms) {
        this.platform = platform;
        this.sms = sms;
        initSmsStrategy();
    }

    /**
     * 初始化短信策略
     */
    private void initSmsStrategy() {
        for (PlatformEnum platformEnum : PlatformEnum.values()) {
            if (Optional.ofNullable(sms).isPresent()) {
                Function<Sms, SmsStrategy> function = platformEnum.getFunction();
                strategy.put(platformEnum.getPlatform(), function.apply(sms.get(platformEnum.getPlatform())));
            }
        }
    }

    /**
     * 创建短信策略
     *
     * @return
     */
    public SmsStrategy getSmsStrategy() {
        if (CollectionUtil.isEmpty(strategy)) {
            throw new CustomSendException(SendEnum.SEND_PLATFORM_NOT_EXIST);
        }
        SmsStrategy smsStrategy = strategy.get(platform);
        if (Objects.isNull(smsStrategy)) {
            throw new CustomSendException(SendEnum.SEND_PLATFORM_NOT_EXIST);
        }
        return smsStrategy;
    }
}
